package com.dataseek.iot.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dataseek.iot.sys.entity.Menu;
import com.dataseek.iot.sys.service.DbService;
import com.dataseek.iot.sys.service.MenuService;
import com.dataseek.iot.sys.service.SysUserService;
import com.dataseek.iot.toolikit.common.util.CustomBeanUtils;
import com.dataseek.iot.toolkit.auth.entity.LoginUser;
import com.dataseek.iot.toolkit.auth.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class CustomUserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private DbService dbService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //查询用户信息
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",userName);
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        if(Objects.isNull(sysUser)){
            throw new RuntimeException("用户名或者密码错误,未查到该用户信息!");
        }
        //查询对应权限信息
        List<String> permissions = new ArrayList<>();
        List<Menu> menuList = menuService.queryMenuTree(sysUser.getUserId());
        JSONArray array = null;
        if(menuList!=null&&menuList.size()>0){
            array= JSONArray.parseArray(JSON.toJSONString(menuList));
            array= CustomBeanUtils.allLevelSort(array,"orderNum","children",false);
            permissions = JSONObject.parseArray(array.toJSONString(), String.class);
        }
        log.info("permissionss" + permissions);
        //把数据封装回UserDetails返回
        return new LoginUser(sysUser,permissions);
    }
}
